//
//  MainRecordVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/20.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MainRecordVC.h"
#import "loginVC.h"

#import "GameRecordCell.h"
#import "HWPopTool.h"
#import "ControlButton.h"
#import "MahjongAttributeCVC.h"
#import "ResultTableViewCell.h"
#import "ChartHeaderView.h"

#import "PatternModel.h"
#import "GameModel.h"
#import "ActionModel.h"
#import "ResultModel.h"

#import "WebSocketUtil.h"

@interface MainRecordVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *GameCollectionView;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;
@property (weak, nonatomic) IBOutlet UILabel *baseAndtimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *networkLabel;
@property (weak, nonatomic) IBOutlet UIButton *indexGameBtn;

@property (nonatomic,strong) UILabel *tipLabel;

@property (nonatomic,strong) UITableView *controlTableView;
@property (nonatomic,strong) UITableView *resultTableView;
@property (nonatomic,strong) UICollectionView *attrCollectionView;
@property (nonatomic,strong) ChartHeaderView *chartHeaderView;

//data
@property (nonatomic,assign) CGFloat modalViewW;
@property (nonatomic,assign) CGFloat modalViewH;
@property (nonatomic,assign) ControlType controlType;
@property (nonatomic,strong) PatternModel *patternModel;
@property (nonatomic,strong) GameModel *currentGameModel;
@property (nonatomic,strong) ActionModel *selectedTagAction;

@property (nonatomic,strong) NSMutableArray *resultActionArr;
@property (nonatomic,strong) NSArray *attributeNameArr;
@property (nonatomic,strong) NSMutableArray *gameArr;
@property (nonatomic,strong) NSArray *selectedRuleArr;
@property (nonatomic,strong) NSMutableArray *selectedAttributeNameArr;
@property (nonatomic,strong) NSMutableArray *selectedTargetPlayerArr;
@property (nonatomic,strong) NSArray *leftPlayerArr;//未胡牌的玩家

@property (nonatomic,assign) NSInteger indexOfGame;
@property (nonatomic,strong) PlayerModel *owner;

@property (nonatomic,assign) BOOL isEditAction;

@end

static NSString *kGameRecordCell = @"kGameRecordCell";
static NSString *kMahjongAttributeCVC = @"kMahjongAttributeCVC";
static NSString *kResultTableViewCell = @"ResultTableViewCell";

@implementation MainRecordVC

- (void)loadGames{
    [GameModel gamesOfMatch:_matchModel.matchId success:^(id array) {
//        [self.GameCollectionView.mj_header endRefreshing];
        [_gameArr removeAllObjects];
        [_gameArr addObjectsFromArray:array];
        
        if (_gameArr.count) {
            _tipLabel.hidden = YES;
            _indexOfGame = _gameArr.count - 1;
            _currentGameModel = _gameArr.lastObject;
            [_indexGameBtn setTitle:NSStringFormat(@"第%ld局",_indexOfGame+1) forState:UIControlStateNormal];
        }else{
            [_indexGameBtn setTitle:@"等待玩家加入" forState:UIControlStateNormal];
        }
        
        [_GameCollectionView reloadData];
        if (_gameArr.count) {
            [_GameCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_indexOfGame inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }
    } fail:^(NSString *errorStr) {
//        [self.GameCollectionView.mj_header endRefreshing];
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)newGame{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Matches/%@/games",_matchModel.matchId)];
    NSDictionary *param = @{};
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
        
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectCallBack) name:NOTIFICATION_CONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(errorCallBack) name:NOTIFICATION_ERROR_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(disConnectCallBack) name:NOTIFICATION_DISCONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newGameCallBack:) name:NOTIFICATION_NEWGAME_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionCallBack:) name:NOTIFICATION_ACTION_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchCallBack:) name:NOTIFICATION_MATCH_CALLBACK object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initUI];
//    _GameCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self loadGames];
//    }];
    [_GameCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GameRecordCell class]) bundle:nil] forCellWithReuseIdentifier:kGameRecordCell];
    
    [self loadGames];
}

- (void)initData{
    //加载pattern
    [PatternModel loadPatternDataSuccess:^(id model) {
        _patternModel = model;
    } fail:^(NSString *errorStr) {}];
    _owner = _matchModel.me;
    _selectedRuleArr = _matchModel.rules;
    _gameArr = [NSMutableArray new];
    _selectedAttributeNameArr = [NSMutableArray new];
    _selectedTargetPlayerArr = [NSMutableArray new];
    
    _modalViewW = SWidth() * 4/5;//modal 宽度
    _modalViewH = SHeight() * 4/5;//modal 高度
    
    if (_matchModel.rules.count) {
        _ruleLabel.text = NSStringFormat(@"牌局规则:%@",[_matchModel.rules componentsJoinedByString:@","]);
    }else{
        _ruleLabel.text = @"";
    }
    _baseAndtimeLabel.text = NSStringFormat(@"底:%ld 限番:%ld",_matchModel.base,_matchModel.ceiling);
    
    _indexGameBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    
}

- (void)initUI{
    _tipLabel = self.tipLabel;
    [self.view addSubview:_tipLabel];
    [self setTipLabelText:_matchModel.players];
}

#pragma mark - private method
- (IBAction)gangAction:(id)sender {
    [self resetSelectedData];
    _isEditAction = NO;
    _controlType = ControlTypeGang;
    [self.controlTableView reloadData];
    [self showModalWithView:self.controlTableView];
}
- (IBAction)huAction:(id)sender {
    [self resetSelectedData];
    _isEditAction = NO;
    _controlType = ControlTypeHu;
    [self.controlTableView reloadData];
    [self showModalWithView:self.controlTableView];
}
- (IBAction)chaAction:(id)sender {
    [self resetSelectedData];
    _isEditAction = NO;
    _controlType = ControlTypeCha;
    [self.controlTableView reloadData];
    [self showModalWithView:self.controlTableView];
}

- (IBAction)newGameAction:(id)sender {
    [self newGame];
}

- (IBAction)gameDataAction:(id)sender {
    [self detailActionResult];
}

- (IBAction)graphAction:(id)sender {
    if (!_chartHeaderView) {
        _chartHeaderView = [[ChartHeaderView alloc]initWithFrame:CGRectMake(20, 20, SWidth() - 40, _modalViewH) gameArr:_gameArr matchModel:_matchModel];
    }
    [_chartHeaderView updateChartGameArr:_gameArr matchModel:_matchModel];
    [self showModalWithView:_chartHeaderView];
}

- (IBAction)logoutAction:(id)sender {
    [UIAlertView showWithTitle:@"警告" message:@"确定要退出？" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView * _Nonnull alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            UIViewController *vc =self.presentingViewController;
            while (![vc isKindOfClass:[loginVC class]]) {
                vc = vc.presentingViewController;
            }
            [vc dismissViewControllerAnimated:YES completion:^{}];
        }
    }];
}
- (IBAction)indexGameAction:(id)sender {
    
}
#pragma mark - 弹框
- (void)showModalWithView:(UIView*)view{
    view.layer.cornerRadius = 10.f;
    view.layer.masksToBounds = YES;
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeGradient;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeRight;
    [[HWPopTool sharedInstance] showWithPresentView:view animated:NO];
}
#pragma mark - 操作表
- (UITableView *)controlTableView{
    if (!_controlTableView) {
        _controlTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,  _modalViewW, _modalViewH)];
        _controlTableView.delegate = self;
        _controlTableView.dataSource = self;
        _controlTableView.showsVerticalScrollIndicator = NO;
        _controlTableView.scrollEnabled = NO;
    }
    return _controlTableView;
}

- (UITableView *)resultTableView{
    if (!_resultTableView) {
        _resultTableView =  [[UITableView alloc]initWithFrame:CGRectMake(0, 60, _modalViewW, _modalViewH - 160)];
        _resultTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _resultTableView.delegate = self;
        _resultTableView.dataSource = self;
        _resultTableView.showsVerticalScrollIndicator = NO;
        [_resultTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ResultTableViewCell class]) bundle:nil] forCellReuseIdentifier:kResultTableViewCell];
        _resultTableView.tableFooterView = [UIView new];
    }
    return _resultTableView;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _controlTableView){
        return 3;
    }
    return _resultActionArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _controlTableView) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"controlTableViewID"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            [self loadNaviCell:cell];
        }else if (indexPath.row == 1){
            if (_controlType == ControlTypeGang){
                //杠
                _attributeNameArr = _patternModel.gangPatternArr;
                [self loadGangCell:cell];
            }else if(_controlType == ControlTypeHu){
                //胡
                _attributeNameArr = _patternModel.huPatternArr;
                [self loadAttributeCell:cell];
            }else{
                //查
                _attributeNameArr = _patternModel.chaPatternArr;
                [self loadAttributeCell:cell];
            }
        }else if (indexPath.row == 2){
            [self loadPlayerCell:cell];
        }
        return cell;
    }else{
        ResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kResultTableViewCell forIndexPath:indexPath];
        cell.owner = _owner;
        cell.cellIdx = indexPath.row;
        cell.resultActionArr = _resultActionArr;
        cell.actionModel = _resultActionArr[indexPath.row];
        return cell;
    }
}

#pragma mark - socket通知:GameCallBackDelegate

- (void)connectCallBack{
    _networkLabel.text = @"网络正常";
    [self loadGames];
}

- (void)errorCallBack{
    _networkLabel.text = @"连接出错";
}

- (void)disConnectCallBack{
    _networkLabel.text = @"连接已断开";
}

- (void)newGameCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    GameModel *mm = [GameModel gameModelPushParse:data];
    [_gameArr addObject:mm];
    if (_gameArr.count) {
        _tipLabel.hidden = YES;
    }
    [_GameCollectionView reloadData];
    
    _currentGameModel = _gameArr.lastObject;
    _indexOfGame = _gameArr.count - 1;
    if (_indexOfGame>0) {
        
    }
    [_GameCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_indexOfGame inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

- (void)actionCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    GameModel *returnGameModel = [GameModel gameModelPushParse:data];
    for (int i=0;i<_gameArr.count;i++) {
        GameModel *gm = _gameArr[i];
        if ([returnGameModel.gameId isEqualToString:gm.gameId]) {
            [_gameArr replaceObjectAtIndex:i withObject:returnGameModel];
            [_GameCollectionView reloadData];
            break;
        }
    }
}

- (void)matchCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    _matchModel = [MatchModel parseDic:data];
    _matchModel.me = _owner;
    NSMutableArray *othersArr = [NSMutableArray new];
    for (PlayerModel *pm in _matchModel.players) {
        if (![pm.playerId isEqualToString:_owner.playerId]) {
            [othersArr addObject:pm];
        }
    }
    _matchModel.others = othersArr;
    _selectedRuleArr = _matchModel.rules;
    [self setTipLabelText:_matchModel.players];
}

- (UILabel *)tipLabel{
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _GameCollectionView.frame.size.width, 40)];
    label.center = CGPointMake(_GameCollectionView.center.x, _GameCollectionView.center.y + 40);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor grayColor];
    label.font = DefaultSystemFont(20);
    return label;
}

- (void)setTipLabelText:(NSArray*)players{
    NSMutableArray *tmp = [NSMutableArray new];
    for (PlayerModel *pm in players) {
        [tmp addObject:pm.playerName];
    }
    _tipLabel.text = NSStringFormat(@"进入房间的玩家:%@",[tmp componentsJoinedByString:@","]);
    if (players.count >= 4) {
        _tipLabel.hidden = YES;
    }else{
        _tipLabel.hidden = NO;
    }
}

#pragma mark - control modal
- (void)loadNaviCell:(UITableViewCell*)cell{
    //title
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake((_modalViewW - 200)/2, 10, 200, 60)];
    titleLabel.text = _controlType == ControlTypeGang?@"杠":(_controlType == ControlTypeHu?@"胡":@"查叫");
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = DefaultSystemFont(30);
    titleLabel.textColor = [UIColor grayColor];
    [cell.contentView addSubview:titleLabel];
    
    ControlButton *sureBtn = [[ControlButton alloc]initWithTitle:@"确定" fontSize:23];
    sureBtn.frame = CGRectMake(_modalViewW - 140, 10, 100, 60);
    [cell.contentView addSubview:sureBtn];
    //确定
    [sureBtn addTapBlock:^(UIButton *btn) {
        [self sendAction];
    }];
    
    
    if (_isEditAction) {
        ControlButton *delBtn = [[ControlButton alloc]initWithTitle:@"删除" fontSize:23];
        delBtn.layer.borderColor = [UIColor redColor].CGColor;
        [delBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        delBtn.frame = CGRectMake(_modalViewW - 140 - 120, 10, 100, 60);
        [cell.contentView addSubview:delBtn];
        //删除按钮
        [delBtn addTapBlock:^(UIButton *btn) {
            [ActionModel deleteActionByGameId:_currentGameModel.gameId actionId:_selectedTagAction.actionId success:^(id model) {
                [[HWPopTool sharedInstance] closeWithBlcok:^{}];
            } fail:^(NSString *errorStr) {
                [Hud hudText:errorStr inView:self.view];
                [[HWPopTool sharedInstance] closeWithBlcok:^{}];
            }];
        }];
    }
}
#pragma mark - 发送Action
- (void)sendAction{
    if (_selectedTargetPlayerArr.count ==0) {
        [Hud hudText:@"请选择玩家" inView:[self getCurrentVC].view];
        return;
    }
    NSString *url = NSStringFormat(@"%@/Games/%@/actions",BASE_URL,_currentGameModel.gameId);
    NSMutableArray *tmp = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [tmp addObject:@{
                         @"id":pm.playerId,
                         @"name":pm.playerName
                         }];
    }
    
    NSDictionary *param = @{
                            @"type":_controlType == ControlTypeGang?@"杠":(_controlType == ControlTypeHu?@"胡":@"查叫"),
                            @"attributes":_selectedAttributeNameArr,
                            @"owner":@{
                                    @"id":_owner.playerId,
                                    @"name":_owner.playerName
                                    },
                            @"targets":tmp
                            };
    if (_isEditAction) {
        [ActionModel putActionByGameId:_currentGameModel.gameId actionId:_selectedTagAction.actionId param:param success:^(id model) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        }];
    }else{
        [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
            [[HWPopTool sharedInstance] closeWithBlcok:^{}];
        }];
    }
}

- (void)loadGangCell:(UITableViewCell*)cell{
    CGFloat margin = 40;
    CGFloat w = (_modalViewW - 4*margin)/3;
    CGFloat h = 100;
    CGFloat y = (_modalViewH - 100 - 160 - h)/2;
    
    for (int i=0; i<_patternModel.gangPatternArr.count; i++) {
        ControlButton *btn = [[ControlButton alloc]initWithTitle:_patternModel.gangPatternArr[i] fontSize:30 bgColor:UIColorHex(EAEAEA)];
        btn.frame = CGRectMake((i+1)*margin + i*w, y, w, h);
        [cell.contentView addSubview:btn];
        [btn addTapBlock:^(UIButton *btn) {
            [self gangTap:cell btn:btn];
        }];
        
        if (_isEditAction && [_patternModel.gangPatternArr[i] isEqualToString:[_selectedAttributeNameArr firstObject]]) {
            btn.backgroundColor = [UIColor redColor];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}
- (void)gangTap:(UITableViewCell*)cell btn:(UIButton*)btn{
    for (UIView *v in cell.contentView.subviews) {
        if ([v isKindOfClass:[ControlButton class]]) {
            v.backgroundColor = UIColorHex(EAEAEA);
            UIButton *b = (UIButton*)v;
            [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
    }
    [_selectedAttributeNameArr removeAllObjects];
    [_selectedAttributeNameArr addObject:btn.titleLabel.text];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_selectedTargetPlayerArr removeAllObjects];
    if ([_selectedAttributeNameArr containsObject:@"暗杠"]||[_selectedAttributeNameArr containsObject:@"补杠"]) {
        if ([_selectedRuleArr containsObject:@"血流成河"]) {
            [_selectedTargetPlayerArr addObjectsFromArray:_matchModel.others];
        }else{
            [_selectedTargetPlayerArr addObjectsFromArray:_leftPlayerArr];
        }
    }else{
        if ([_selectedRuleArr containsObject:@"血流成河"]) {
            [_selectedTargetPlayerArr addObject:_matchModel.others.firstObject];
        }else{
            if (_leftPlayerArr.count) {
                [_selectedTargetPlayerArr addObject:_leftPlayerArr.firstObject];
            }
        }
    }
    [_controlTableView reloadRow:2 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
}

- (void)loadAttributeCell:(UITableViewCell*)cell{
    if (!_attrCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumLineSpacing = 0;
        _attrCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, _modalViewW, _modalViewH - 60 - 160) collectionViewLayout:flowLayout];
        _attrCollectionView.backgroundColor = [UIColor clearColor];
        _attrCollectionView.delegate = self;
        _attrCollectionView.dataSource = self;
        _attrCollectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
        [_attrCollectionView registerClass:[MahjongAttributeCVC class] forCellWithReuseIdentifier:kMahjongAttributeCVC];
    }
    [_attrCollectionView reloadData];
    [cell.contentView addSubview:_attrCollectionView];
}

- (void)loadPlayerCell:(UITableViewCell*)cell{
    CGFloat w = 140;
    CGFloat y = 10;
    CGFloat margin = (_modalViewW - 3*w)/4;
    
    NSMutableArray *selectedPlayerIdArr = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [selectedPlayerIdArr addObject:pm.playerId];
    }
    
    //已胡玩家
    NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
    for (ActionModel *am in _currentGameModel.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            [gonePlayerIdArr addObject:am.owner.playerId];
        }
    }
    
    for (int i=0 ; i<_matchModel.others.count ; i++) {
        PlayerModel *pm = _matchModel.others[i];
        ControlButton *btn = [[ControlButton alloc]initWithTitle:pm.playerName fontSize:34 cornerRadius:w/2];
        btn.frame = CGRectMake((i+1)*margin+i*w, y, w, w);
        [cell.contentView addSubview:btn];
        
        if ([selectedPlayerIdArr containsObject:pm.playerId]) {
            btn.layer.borderColor = [UIColor redColor].CGColor;
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            btn.layer.borderWidth = 0;
            [btn setBackgroundImage:UIImageWithName(@"player_selected") forState:UIControlStateNormal];
            
            [btn addTapBlock:^(UIButton *btn) {
                [self playerTap:cell btn:btn];
            }];
        }else{
            if (![_selectedRuleArr containsObject:@"血流成河"] && [gonePlayerIdArr containsObject:pm.playerId]) {
                btn.layer.borderColor = [UIColor grayColor].CGColor;
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                btn.layer.borderWidth = 0;
                [btn setBackgroundImage:UIImageWithName(@"playerWin") forState:UIControlStateNormal];
            }else{
                btn.layer.borderColor = [UIColor grayColor].CGColor;
                [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                btn.layer.borderWidth = 0;
                [btn setBackgroundImage:UIImageWithName(@"player_unSelect") forState:UIControlStateNormal];
                
                [btn addTapBlock:^(UIButton *btn) {
                    [self playerTap:cell btn:btn];
                }];
            }
        }
    }
}

- (void)playerTap:(UITableViewCell*)cell btn:(UIButton*)btn{
    //点击的玩家
    PlayerModel *pm;
    for (PlayerModel *p in _matchModel.players) {
        if ([p.playerName isEqualToString:btn.titleLabel.text]) {
            pm = p;
            break;
        }
    }
    
    NSMutableArray *tmpPlayerIdArr = [NSMutableArray new];
    for (PlayerModel *pm in _selectedTargetPlayerArr) {
        [tmpPlayerIdArr addObject:pm.playerId];
    }
    
    if ([tmpPlayerIdArr containsObject:pm.playerId]) {
        for (PlayerModel *p in _selectedTargetPlayerArr) {
            if ([p.playerId isEqualToString:pm.playerId]) {
                [_selectedTargetPlayerArr removeObject:p];
                break;
            }
        }
        btn.layer.borderColor = [UIColor grayColor].CGColor;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = 0;
        [btn setBackgroundImage:UIImageWithName(@"player_unSelect") forState:UIControlStateNormal];
    }else{
        
        if ([_selectedAttributeNameArr.firstObject isEqualToString:@"直杠"] || (NSNotFound == [_selectedAttributeNameArr indexOfObject:@"杠上花"] && NSNotFound == [_selectedAttributeNameArr indexOfObject:@"自摸"])) {
            if (_controlType != ControlTypeCha) {
                [_selectedTargetPlayerArr removeAllObjects];
            }
            [_selectedTargetPlayerArr addObject:pm];
            [_controlTableView reloadRow:2 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [_selectedTargetPlayerArr addObject:pm];
        }
        
        btn.layer.borderColor = [UIColor redColor].CGColor;
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        btn.layer.borderWidth = 0;
        [btn setBackgroundImage:UIImageWithName(@"player_selected") forState:UIControlStateNormal];
    }
}

- (void)resetSelectedData{
    
    [_selectedAttributeNameArr removeAllObjects];
    [_selectedTargetPlayerArr removeAllObjects];
    
    [_controlTableView reloadData];
    [_GameCollectionView reloadData];
}

#pragma mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _attrCollectionView) {
        return _attributeNameArr.count;
    }
    return _gameArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _attrCollectionView) {
        MahjongAttributeCVC *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kMahjongAttributeCVC forIndexPath:indexPath];
        
        NSString *attribute = _attributeNameArr[indexPath.row];
        cell.titleLabel.text = attribute;
        cell.titleLabel.textColor = [UIColor grayColor];
        
        if ([_selectedAttributeNameArr containsObject:attribute]) {
            cell.titleLabel.backgroundColor = [UIColor redColor];
            cell.titleLabel.textColor = [UIColor whiteColor];
        }else{
            cell.titleLabel.backgroundColor = UIColorHex(EAEAEA);
            cell.titleLabel.textColor = [UIColor grayColor];
        }
        
        return cell;
    }
    GameRecordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kGameRecordCell forIndexPath:indexPath];
    if (indexPath.row%2) {
        cell.backgroundColor = UIColorHex(#EEEEEE);
    }else{
        cell.backgroundColor = UIColorHex(#E9E9E9);
    }
    cell.owner = _owner;
    cell.height = _GameCollectionView.frame.size.height;
    cell.gameModel = _gameArr[indexPath.row];
#pragma mark - 标签事件tagAction
    cell.getTagClickBlock = ^(id data){
        ActionModel *am = data;
        _isEditAction = YES;
        _selectedTagAction = data;
        _currentGameModel = _gameArr[indexPath.row];
        [self leftPlayers];
        [self resetSelectedData];
        
//        _selectedActionName = am.actionType;
        [_selectedAttributeNameArr addObjectsFromArray:am.attributesArr];
        [_selectedTargetPlayerArr addObjectsFromArray:am.targetsArr];
        [self.controlTableView reloadData];
        [self showModalWithView:self.controlTableView];
    };
    return cell;
}
#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _attrCollectionView) {
        MahjongAttributeCVC *cell = (MahjongAttributeCVC*)[collectionView cellForItemAtIndexPath:indexPath];
        NSString *title = cell.titleLabel.text;
        if ([_selectedAttributeNameArr containsObject:title]) {
            [_selectedAttributeNameArr removeObject:title];
        }else{
            [_selectedAttributeNameArr addObject:title];
        }
        
        if ([_selectedAttributeNameArr containsObject:@"自摸"]||[_selectedAttributeNameArr containsObject:@"杠上花"]) {
            [_selectedTargetPlayerArr removeAllObjects];
            if ([_selectedRuleArr containsObject:@"血流成河"]) {
                [_selectedTargetPlayerArr addObjectsFromArray:_matchModel.others];
            }else{
                [_selectedTargetPlayerArr addObjectsFromArray:_leftPlayerArr];
            }
        }else{
            PlayerModel *tmp = _selectedTargetPlayerArr.firstObject;
            [_selectedTargetPlayerArr removeAllObjects];
            if (tmp) {
                [_selectedTargetPlayerArr addObject:tmp];
            }
        }
        
        [_controlTableView reloadRow:2 inSection:0 withRowAnimation:UITableViewRowAnimationNone];
        [_attrCollectionView reloadData];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView != _attrCollectionView) {
        NSIndexPath *firstIndexPath = [[collectionView indexPathsForVisibleItems] firstObject];
        _indexOfGame = firstIndexPath.row;
        _currentGameModel = _gameArr[_indexOfGame];
        [_indexGameBtn setTitle:NSStringFormat(@"第%ld局",_indexOfGame + 1) forState:UIControlStateNormal];
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _attrCollectionView) {
        return CGSizeMake((_modalViewW-90)/5, (_modalViewW-90)/5*0.6);
    }
    return CGSizeMake(_GameCollectionView.frame.size.width,_GameCollectionView.frame.size.height);
}
/**
 *  section的内边距
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (collectionView == _attrCollectionView) {
        return UIEdgeInsetsMake(5, 5, 5, 5);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/**
 *  section之间的行距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (collectionView == _attrCollectionView) {
        return 10;
    }
    return 0;
}
/*
 *  item之间的间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (collectionView == _attrCollectionView) {
        return 5;
    }
    return 0;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _resultTableView){
        return 60.f;
    }else{
        NSInteger row = indexPath.row;
        switch (row) {
            case 0:
                return 80.f;
                break;
            case 1:
                return _modalViewH - 80 - 160;
                break;
            case 2:
                return 160.f;
                break;
                
            default:
                break;
        }
        return 0.f;
    }
}
#pragma mark - private
- (void)leftPlayers{
    //已胡玩家
    NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
    for (ActionModel *am in _currentGameModel.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            [gonePlayerIdArr addObject:am.owner.playerId];
        }
    }
    //未胡玩家
    NSMutableArray *leftPlayerArr = [NSMutableArray new];
    for (PlayerModel *pm in _matchModel.others) {
        if (![gonePlayerIdArr containsObject:pm.playerId]) {
            [leftPlayerArr addObject:pm];
        }
    }
    _leftPlayerArr = leftPlayerArr;
}

- (void)detailActionResult{
    //获取与自己相关的action
    _resultActionArr = [NSMutableArray new];
    [_resultActionArr addObjectsFromArray:_currentGameModel.actionArr];
    for (ActionModel *am in _currentGameModel.actionArr) {
        BOOL flag = NO;
        if ([am.owner.playerId isEqualToString:_owner.playerId]) {
            flag = YES;
        }
        for (PlayerModel *pm in am.targetsArr) {
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        for (PlayerModel *pm in am.caguaArr) {//擦挂
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        if ([am.transferedTo.playerId isEqualToString:_owner.playerId]) {//转雨
            flag = YES;
        }
        if (!flag) {
            [_resultActionArr removeObject:am];
        }
    }
    
    UIView *cv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _modalViewW, _modalViewH)];
    //titleLabel
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _modalViewW, 60)];
    label.textAlignment = NSTextAlignmentCenter;
    NSInteger score = 0;
    for (ResultModel *rm in _currentGameModel.resultArr) {
        if ([rm.playerModel.playerId isEqualToString:_owner.playerId]) {
            score = rm.score;
            break;
        }
    }
    NSString *scoreStr = score>0?NSStringFormat(@"本局当前输赢: %ld",score):NSStringFormat(@"本局当前输赢: %ld",score);
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:scoreStr];
    UIColor *tmpColor = score>0?[UIColor redColor]:UIColorHex(#8BB335);
    if (score == 0) {
        tmpColor = [UIColor grayColor];
    }
    [attrStr addAttribute:NSForegroundColorAttributeName value:tmpColor range:NSMakeRange(8, scoreStr.length - 8)];
    [attrStr addAttribute:NSForegroundColorAttributeName value:tmpColor range:NSMakeRange(8, scoreStr.length - 8)];
    label.attributedText = attrStr;
    label.font = [UIFont boldSystemFontOfSize:25];
    label.backgroundColor = [UIColor whiteColor];
    [cv addSubview:label];
    //resultTableView
    [cv addSubview:self.resultTableView];
    //sureBtn
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, _modalViewH - 100, _modalViewW, 100)];
    view.backgroundColor = [UIColor whiteColor];
    ControlButton *sureBtn = [[ControlButton alloc]initWithTitle:@"确 定" fontSize:20 bgColor:UIColorHex(#EE8222)];
    sureBtn.layer.cornerRadius = 10.f;
    sureBtn.frame = CGRectMake((_modalViewW - 300)/2, 10, 300, 80);
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTapBlock:^(UIButton *btn) {
        [[HWPopTool sharedInstance] closeWithBlcok:^{}];
    }];
    [view addSubview:sureBtn];
    [cv addSubview:view];
    
    [_resultTableView reloadData];
    [self showModalWithView:cv];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
